#include "rec_nec.h"

//检测是否接收到码头了
unsigned char nec_start;

unsigned char nec_lowTime;
unsigned char nec_highTime;
unsigned char nec_lowTimePrev;
unsigned char nec_highTimePrev;

unsigned short nec_usercode;
unsigned short nec_tempdata;
unsigned char nec_step;
unsigned char nec_recOk;

unsigned short nec_dataBuff;

unsigned char prevDat;

//记录多久没有收到nec数据了
unsigned char nec_notRecTime = 0;

void NEC_Rec(unsigned char dat)
{
	if(nec_notRecTime >= 5)
	{
		nec_start = 0;
	}
	nec_notRecTime = 0;
	if(dat)
	{
		nec_highTime ++;
		if(prevDat != dat)//说明电平变高后第一次进来
		{
			nec_lowTimePrev = nec_lowTime;
			if(nec_start==0)
			{
				nec_start = 1;
			}
		}
		nec_lowTime = 0;
	}
	else
	{
		nec_lowTime ++;
		if(prevDat != dat)//说明电平变低后第一次进来
		{
			nec_highTimePrev = nec_highTime;
			if(nec_start==1)
			{
				if((nec_highTime >= 34)&&(nec_lowTimePrev >= 70))//4.5毫秒高电平
				{
					nec_start = 2;//说明码头接收完成了
					nec_step = 0;
					nec_tempdata = 0;
					nec_recOk = 0;
					nec_usercode = 0;
				}
				else
				{
					nec_start = 0;
				}
			}
			else if(nec_start == 2)
			{
				if((nec_highTime<=5)&&(nec_lowTimePrev>=3))//高电平时间为560us的话为0
				{
					nec_step ++;
					if(nec_step>=17)
					{
						nec_tempdata <<= 1;
					}
					else
					{
						nec_usercode <<= 1;
					}
					if((nec_step>=32)&&(nec_usercode==0x00ff))
					{
						nec_dataBuff = nec_tempdata;
						nec_recOk = 1;
						nec_start = 0;
					}
				}
				else if((nec_highTime > 10)&&(nec_lowTimePrev>=3))//高电平时间为1.69毫秒的话为1
				{
					nec_step ++;
					if(nec_step>=17)
					{
						nec_tempdata <<= 1;
						nec_tempdata += 1;
					}
					else
					{
						nec_usercode <<= 1;
						nec_usercode += 1;
					}
					if((nec_step>=32)&&(nec_usercode==0x00ff))
					{
						nec_dataBuff = nec_tempdata;
						nec_recOk = 1;
						nec_start = 0;
					}
				}
				else
				{
					//数据异常
					nec_start = 0;
					nec_step = 0;
					nec_tempdata = 0;
					nec_recOk = 0;
				}
			}
		}
		nec_highTime = 0;
	}
	prevDat = dat;
}
